<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Auth;

class UserController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function users()
    {
        $query = DB::table('anli');
        $results = $query->get();
        return $this->create($results, '获取成功', 200);
    }

    // 登录
    public function login(Request $request)
    {
        $searchParams = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);
        // 根据POST参数构建查询条件
        $results = User::where('username', $searchParams['username'])->first();
        // 判断结果
        if (!$results) {
            // 账号不存在
            return $this->create(['error' => '账号不存在'], '登录失败', 404);
        }
        if ($results->password !== $searchParams['password']) {
            // 密码错误
            return $this->create(['err or' => '账号或密码错误'], '登录失败', 401);
        }
        $token = JWTAuth::fromUser($results);
        $data = [
            'user' => $results,
            'token' => $token,
        ];
        // 登录成功
        return $this->create($data, '登录成功', 'success', 200);
    }

    //注册
    public function rules(Request $request)
    {
        $searchParams = $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
            'phone' => 'required|string',
            'age' => 'required|string',
            'sex' => 'required|string',
            'avater' => 'required|string',
        ]);
        $usernameres = User::where('username', $searchParams['username'])->exists();
        if ($usernameres) {
            return $this->create([
                'msg' => '用户名已存在',
                'code' => 400,
            ]);
        } else {
            $userData = [
                'username' => $searchParams['username'],
                'password' => $searchParams['password'],
                'phone' => $searchParams['phone'],
                'age' => $searchParams['age'],
                'sex' => $searchParams['sex'],
                'avater' => $searchParams['avater'],
            ];
            DB::table('users')->insert($userData);
            $data = [
                'message' => '创建成功'
            ];
            return $this->create($data, 200);
        }
    }
}
